﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Web;
using EOSCRM.Domain;
using EOSCRM.Util;
using System.Configuration;


namespace EOSCRM.Dao
{
    public class ConfigDao : BaseDao
    {
        protected static string _SESSION_ID = "_CRM_CONFIG_";
        protected Dictionary<string, string> _configsList = new Dictionary<string, string>();

        public ConfigDao()
        {
            LoadConfigs();
        }

        private void LoadConfigs()
        {
            var oQuery = _db.Configs.ToList();
            _configsList.Clear();

            foreach (var t in oQuery)
                _configsList.Add(t.Name.ToUpper(), t.Value);

            //HttpContext.Current.Session[_SESSION_ID] = _configsList;
        }

        public static string Value(string configName)
        {
            var resValue = "";
            try
            {
                var dictionary = HttpContext.Current.Session[_SESSION_ID] as Dictionary<string, string>;
                if (dictionary != null)
                    dictionary.TryGetValue(configName.ToUpper(), out resValue);
            }
            catch { }

            return resValue ?? "";
        }

        public void Save(string configName, string configValue)
        {
            configName = configName.ToUpper();
            if (_db.Configs.Count(w => w.Name == configName) == 0)
                _db.Configs.InsertOnSubmit(new Config { Name = configName, Value = configValue });
            else
            {
                var curConfig = _db.Configs.SingleOrDefault(w => w.Name == configName);
                if (curConfig != null) 
                    curConfig.Value = configValue;
            }
            _db.SubmitChanges();
        }

        public Config GetConFig(String Name){
            return _db.Configs.Where(p => p.Name.Equals(Name)).FirstOrDefault();
        }
        public List<Config> GetListStartWith(String startWith)
        {
            return _db.Configs.Where(p => p.Name.StartsWith(startWith)).ToList();
        }
        public Message UpdateGia(string giathuhoach, string giathumua, string giaban)
        {
            try
            {
                _db.UPDATEGIA(giathuhoach, giathumua, giaban);
                return new Message(MessageConstants.I_UPDATE_SUCCEED, MessageType.Info);
            }
            catch (Exception ex)
            {
                return new Message(MessageConstants.E_UPDATE_FAILED_EXCEPTION, MessageType.Error);
            }

        }
    }
}
